package com.teamclub.erp.sservices

import java.util.List

import io.ebean.{Ebean, ExpressionList}
import com.google.common.collect.Lists
import com.teamclub.domain.erp.dealer.DealerInfoLink
import com.teamclub.domain.system.AppDomainInstance
import com.teamclub.erp.sforms.SignedManagerForm
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.springframework.stereotype.Service
import scala.collection.JavaConversions._

@Service
class SignedManagerService {

  def expr(where: ExpressionList[DealerInfoLink], form: SignedManagerForm) = {
    if(StringUtils.isNotBlank(form.dealerOrganNo)) {
      where.eq("dealerOrganNo", form.dealerOrganNo)
    }
    if(StringUtils.isNotBlank(form.producerOrganNo)) {
      where.eq("producerOrganNo", form.producerOrganNo)
    }
  }

  def list(form: SignedManagerForm): F.Either[List[DealerInfoLink], ErrorCode] = {
    val where = Ebean.find(classOf[DealerInfoLink]).where()
    expr(where, form)
    val list = where.findList()
    F.Either.Left(list)
  }

  def pagerList(form:SignedManagerForm): F.Either[Pager[DealerInfoLink], ErrorCode] = {
    val where = Ebean.find(classOf[DealerInfoLink]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def signedAll(form: SignedManagerForm): F.Either[Boolean, ErrorCode] = {
    val list = Ebean.find(classOf[AppDomainInstance]).where().eq("appDomain", "WINDER-PRODUCER").findList()
    val lists: List[DealerInfoLink] = Lists.newArrayList()
    list.foreach(v => {
      val instance = new DealerInfoLink
      instance.setDealerOrganNo(form.getDealerOrganNo)
      instance.setProducerOrganNo(v.getOrganNo)
      lists.add(instance)
    })
    Ebean.saveAll(lists)
    return F.Either.Left(true)
  }

  def add(form: SignedManagerForm): F.Either[Boolean, ErrorCode] = {
    val lists: List[DealerInfoLink] = Lists.newArrayList()
    if(StringUtils.isNotBlank(form.producerOrganNo)) {
      val instance = new DealerInfoLink
      instance.setDealerOrganNo(form.dealerOrganNo)
      instance.setProducerOrganNo(form.producerOrganNo)
      lists.add(instance)
    }
    if(StringUtils.isNotBlank(form.producerOrganNos)) {
      val producerOrganNos = form.producerOrganNos.split(",")
      for(producerOrganNo <- producerOrganNos) {
        var instance = new DealerInfoLink
        instance.setDealerOrganNo(form.dealerOrganNo)
        instance.setProducerOrganNo(producerOrganNo)
        lists.add(instance)
      }
    }
    Ebean.saveAll(lists)
    F.Either.Left(true)
  }
}
